#!/bin/sh

# If an include wasn't specified in the environment, then search for one...
if [ "x$INCLUDE" = "x" ]; then
    # Locations (in order) to use when searching for an include file.
    for include in `dirname $0`/service.in.sh; do
        if [ -r $include ]; then
            . $include
            break
        fi
    done
# ...otherwise, source the specified include.
elif [ -r $INCLUDE ]; then
    . $INCLUDE
fi

# Use JAVA_HOME if set, otherwise look for java in PATH
if [ -x $JAVA_HOME/bin/java ]; then
    JAVA=$JAVA_HOME/bin/java
else
    JAVA=`which java`
fi

if [ -z $CONF -o -z $CLASSPATH ]; then
    echo "You must set the CONF and CLASSPATH vars" >&2
    exit 1
fi

# Special-case path variables.
case "`uname`" in
    CYGWIN*) 
        CLASSPATH=`cygpath -p -w "$CLASSPATH"`
        CONF=`cygpath -p -w "$CONF"`
    ;;
esac

launch_service()
{
    pidpath=$1
    foreground=$2
    props=$3
    parms="-Dconfig=$CONF \
			-Dapppath=$home -Dappenv=$APPENV"

    if [ "x$pidpath" != "x" ]; then
        parms="$parms -Dpidfile=$pidpath"
    fi
    
    # The foreground option will tell MainDaemon not
    # to close stdout/stderr, but it's up to us not to background.
    if [ "x$foreground" != "x" ]; then
        parms="$parms -Dforeground=yes"
        $JAVA $JVM_OPTS $parms -cp $CLASSPATH $props \
                ServiceDaemon
    # Startup MainDaemon, background it, and write the pid.
    else
        exec $JAVA $JVM_OPTS $parms -cp $CLASSPATH $props \
                    ServiceDaemon <&- &
        [ ! -z $pidpath ] && printf "%d" $! > $pidpath
    fi

    return $?
}

# Parse any command line options.
args=`getopt fhp:bD: "$@"`
eval set -- "$args"

while true; do
    case "$1" in
        -p)
            pidfile="$2"
            shift 2
        ;;
        -f)
            foreground="yes"
            shift
        ;;
        -h)
            echo "Usage: $0 [-f] [-h] [-p pidfile] [-b]"
            exit 0
        ;;
        -D)
            properties="$properties -D$2"
            shift 2
        ;;
        --)
            shift
            break
        ;;
        *)
            echo "Error parsing arguments!" >&2
            exit 1
        ;;
    esac
done

# Start up the service
launch_service "$pidfile" "$foreground" "$properties"

exit $?

# vi:ai sw=4 ts=4 tw=0 et
